class DoubaoAPI {
  constructor(apiKey) {
    this.apiKey = apiKey;
    this.apiUrl = 'https://api.doubao.com/chat/completions';
  }

  // 发送消息到豆包API
  async sendMessage(messages) {
    try {
      const response = await fetch(this.apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`
        },
        body: JSON.stringify({
          model: 'doubao-pro',
          messages,
          temperature: 0.7,
          emotion_analysis: true // 请求情感分析
        })
      });
      
      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status}`);
      }
      
      const data = await response.json();
      return {
        success: true,
        data
      };
    } catch (error) {
      console.error('Error sending message:', error);
      return {
        success: false,
        error: error.message || '发送消息时出错'
      };
    }
  }

  // 分析情感
  async analyzeEmotion(text) {
    try {
      const response = await fetch(this.apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`
        },
        body: JSON.stringify({
          model: 'doubao-pro',
          messages: [
            { role: 'system', content: '你是一个情感分析专家，擅长识别文本中的情感倾向。' },
            { role: 'user', content: `分析以下文本的情感倾向：${text}` }
          ],
          temperature: 0.2 // 低温度以获得更确定性的回答
        })
      });
      
      if (!response.ok) {
        throw new Error(`情感分析请求失败: ${response.status}`);
      }
      
      const data = await response.json();
      const emotion = this.parseEmotionResponse(data.choices[0].message.content);
      
      return {
        success: true,
        emotion
      };
    } catch (error) {
      console.error('Error analyzing emotion:', error);
      return {
        success: false,
        emotion: 'neutral'
      };
    }
  }

  // 解析情感分析结果
  parseEmotionResponse(responseText) {
    // 这里需要根据豆包API实际返回的情感分析格式进行解析
    // 这是一个简化的示例，实际实现需要根据API文档调整
    
    const lowerText = responseText.toLowerCase();
    
    if (lowerText.includes('积极') || lowerText.includes('开心') || lowerText.includes('满意')) {
      return 'positive';
    } else if (lowerText.includes('消极') || lowerText.includes('难过') || lowerText.includes('生气')) {
      return 'negative';
    } else if (lowerText.includes('兴奋') || lowerText.includes('激动') || lowerText.includes('期待')) {
      return 'excited';
    } else if (lowerText.includes('悲伤') || lowerText.includes('沮丧') || lowerText.includes('失望')) {
      return 'sad';
    } else if (lowerText.includes('愤怒') || lowerText.includes('发火') || lowerText.includes('烦躁')) {
      return 'angry';
    } else {
      return 'neutral';
    }
  }
}

export default DoubaoAPI;    